package io.gitee.mingbaobaba.security.starter.response;

import io.gitee.mingbaobaba.security.core.factory.SecurityFactory;
import io.gitee.mingbaobaba.security.core.properties.SecurityProperties;
import io.gitee.mingbaobaba.security.core.response.SecurityResponse;
import io.gitee.mingbaobaba.security.starter.utils.ServletUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>response 实现</p>
 *
 * @author yingsheng.ye
 * @version 1.0.0
 * @since 2023/8/29 9:34
 */
public class SecurityHttpServletResponse implements SecurityResponse {

    @Override
    public Object target() {
        return ServletUtil.getResponse();
    }

    @Override
    public SecurityResponse setHeader(String name, String value) {
        ((HttpServletResponse) target()).setHeader(name, value);
        return this;
    }

    @Override
    public SecurityResponse addHeader(String name, String value) {
        ((HttpServletResponse) target()).addHeader(name, value);
        return this;
    }

    @Override
    public SecurityResponse addCookie(String name, String value) {
        //设置默认24小时
        return addCookie(name, value, 60 * 60 * 24);
    }

    @Override
    public SecurityResponse addCookie(String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        SecurityProperties.CookieProperties cookieProperties = SecurityFactory.getConfig.get().getCookieConfig();
        if (null != cookieProperties) {
            if (null != cookieProperties.getDomain()) {
                cookie.setDomain(cookieProperties.getDomain());
            }
            if (null != cookieProperties.getPath()) {
                cookie.setPath(cookieProperties.getPath());
            }
            if (null != cookieProperties.getSecure()) {
                cookie.setSecure(cookieProperties.getSecure());
            }
            if (null != cookieProperties.getHttpOnly()) {
                cookie.setHttpOnly(cookieProperties.getHttpOnly());
            }
            if (null != cookieProperties.getComment()) {
                cookie.setComment(cookieProperties.getComment());
            }
        }
        cookie.setMaxAge(maxAge);
        ((HttpServletResponse) target()).addCookie(cookie);
        return this;
    }
}
